﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Imdb;
using System.IO;

namespace MoviesManager.UserControls
{
    public partial class IMDBSynchronisation : UserControl
    {
        string moviesFolderPath = @"E:\MoviesMangager";
        Imdb.Services Imdb = new Services();
        FiltersCollection MFiltersCollection = new FiltersCollection();
        VMovieCollection VMCollection = new VMovieCollection();
        VMovie CurrentMovie = new VMovie();
        Movie SelectedMovie = new Movie();

        public VMovieCollection theMovies
        {
            get { return this.VMCollection; }
        }
    
        public IMDBSynchronisation()
        {
            InitializeComponent();
        }

        public void Bind(VMovieCollection vmCollection)
        {
            this.VMCollection = vmCollection;
            foreach (var item in VMCollection)
            {
                item.ImdbSynchronisationDone += new VMovie.ImdbSynchronisation(IMDBSynchDone);
            }

            movieFolderBindingSource1.DataSource = null;
            movieFolderBindingSource1.DataSource = VMCollection;
            lbMoves.DataSource = movieFolderBindingSource1;
            lbMoves.Refresh();
        }

        private void IMDBSynchDone(string movieSynchName)
        {
            lbMoves_SelectedIndexChanged(lbMoves, new EventArgs());
            lbMoves.Refresh();
        }

        private void lstBox_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index != -1)
            {
                //
                // Draw the background of the ListBox control for each item.
                // Create a new Brush and initialize to a Black colored brush
                // by default.
                //
                e.DrawBackground();
                Brush myBrush = Brushes.Black;

                switch (((VMovie)((ListBox)sender).Items[e.Index]).MovieStatus)
                {
                    case moviesStatuses.None:
                        myBrush = Brushes.Black;
                        break;
                    case moviesStatuses.ImdbSynched:
                        myBrush = Brushes.Green;
                        break;
                    case moviesStatuses.ImdbNotSynched:
                        myBrush = Brushes.Red;
                        break;
                    default:
                        break;
                }
                // Draw the current item text based on the current 
                // Font and the custom brush settings.
                //
                e.Graphics.DrawString(((VMovie)(((ListBox)sender).Items[e.Index])).MovieSynhName,
                    e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
                //
                // If the ListBox has focus, draw a focus rectangle 
                // around the selected item.
                //
                e.DrawFocusRectangle();
            }
        }

        private void lbMoves_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListBox movieListBox = (ListBox)sender;
            if (movieListBox.SelectedIndex != -1)
                {
                    CleanImdbInfoControls();
                    switch (((VMovie)movieListBox.SelectedItem).MovieStatus)
                    {
                        case moviesStatuses.None:
                            btnIMDBSingleSynch.Enabled = true;
                            break;
                        case moviesStatuses.ImdbSynched:
                        case moviesStatuses.ImdbNotSynched:
                            btnIMDBSingleSynch.Enabled = false;
                            CurrentMovie = (VMovie)movieListBox.SelectedItem;
                            if (CurrentMovie.MoviesIMDBResultset != null)
                                BindImdbInfoControls();
                            break;
                    }
                }
        }

        private void CleanImdbInfoControls()
        {
            lbPopularTitles.Items.Clear();
            lbPartialMatches.Items.Clear();
            lbExactMatches.Items.Clear();
            lbl_title.Text = string.Empty;
            lbl_year.Text = string.Empty;
            lbl_genres.Text = string.Empty;
            lbl_studio.Text = string.Empty;
            lbl_rating.Text = string.Empty;
            txt_plot.Text = string.Empty;
            pictureBox1.Image = null;
            btnApply.Enabled = false;
            btnIMDBSingleSynch.Enabled = false;
        }

        private void btnIMDBSynch_Click(object sender, EventArgs e)
        {
            btnIMDBSingleSynch.Enabled = false;
            Imdb.FindMovie(((VMovie)lbMoves.SelectedItem).MovieSynhName);
        }

        private void lstBoxMatches_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index != -1)
            {
                //
                // Draw the background of the ListBox control for each item.
                // Create a new Brush and initialize to a Black colored brush
                // by default.
                //
                e.DrawBackground();
                Brush myBrush = Brushes.Black;
                if (CurrentMovie.MovieIMDBInfo != null && ((Movie)((ListBox)sender).Items[e.Index]).Id == CurrentMovie.MovieIMDBInfo.Id)
                {
                    myBrush = Brushes.Green;
                }

                // Draw the current item text based on the current 
                // Font and the custom brush settings.
                //
                e.Graphics.DrawString(((Movie)(((ListBox)sender).Items[e.Index])).Title,
                    e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
                //
                // If the ListBox has focus, draw a focus rectangle 
                // around the selected item.
                //
                e.DrawFocusRectangle();
            }
        }

        private void lbExactMatches_SelectedValueChanged(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            if (lbExactMatches.SelectedIndex != -1)
            {
                var temp = (CurrentMovie.MoviesIMDBResultset.ExactMatches.Find(p => p.Id == ((Movie)lbExactMatches.SelectedItem).Id));
                lbPopularTitles.SelectedIndex = -1;
                lbPartialMatches.SelectedIndex = -1;
                if (CurrentMovie.MovieIMDBInfo != null && ((Movie)lbExactMatches.SelectedItem).Id == CurrentMovie.MovieIMDBInfo.Id)
                {
                    btnApply.Enabled = false;
                    SelectedMovie = CurrentMovie.MovieIMDBInfo;
                    BindImdbMovieDetailInfoControls(SelectedMovie);
                    if (SelectedMovie.Poster == null)
                        Helpers.IMDBHelpers.download_Poster(SelectedMovie);
                    Cursor.Current = Cursors.Arrow;
                }
                else if (temp.AlreadyDownloaded)
                {
                    btnApply.Enabled = true;
                    SelectedMovie = temp;
                    BindImdbMovieDetailInfoControls(CurrentMovie.MoviesIMDBResultset.ExactMatches.Find(p => p.Id == ((Movie)lbExactMatches.SelectedItem).Id));
                    if (temp.Poster == null)
                        Helpers.IMDBHelpers.download_Poster(temp);
                    Cursor.Current = Cursors.Arrow;
                }
                else
                {
                    btnApply.Enabled = true;
                    Imdb.GetMovieAsync(((Movie)lbExactMatches.SelectedItem).Id, false); //0499549 avatar  //0133093 matrix
                }
            }
        }

        private void lbPartialMatches_SelectedValueChanged(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            if (lbPartialMatches.SelectedIndex != -1)
            {
                var temp = (CurrentMovie.MoviesIMDBResultset.PartialMatches.Find(p => p.Id == ((Movie)lbPartialMatches.SelectedItem).Id));
                lbExactMatches.SelectedIndex = -1;
                lbPopularTitles.SelectedIndex = -1;
                if (CurrentMovie.MovieIMDBInfo != null && ((Movie)lbPartialMatches.SelectedItem).Id == CurrentMovie.MovieIMDBInfo.Id)
                {
                    btnApply.Enabled = false;
                    SelectedMovie = CurrentMovie.MovieIMDBInfo;
                    BindImdbMovieDetailInfoControls(SelectedMovie);
                    if (SelectedMovie.Poster == null)
                        Helpers.IMDBHelpers.download_Poster(SelectedMovie);
                    Cursor.Current = Cursors.Arrow;
                }
                else if (temp.AlreadyDownloaded)
                {
                    btnApply.Enabled = true;
                    SelectedMovie = temp;
                    BindImdbMovieDetailInfoControls(CurrentMovie.MoviesIMDBResultset.PartialMatches.Find(p => p.Id == ((Movie)lbPartialMatches.SelectedItem).Id));
                    if (temp.Poster == null)
                        Helpers.IMDBHelpers.download_Poster(temp);
                    Cursor.Current = Cursors.Arrow;
                }
                else
                {
                    btnApply.Enabled = true;
                    Imdb.GetMovieAsync(((Movie)lbPartialMatches.SelectedItem).Id, false); //0499549 avatar  //0133093 matrix
                }
            }

        }

        private void lbPopularTitles_SelectedValueChanged(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            if (lbPopularTitles.SelectedIndex != -1)
            {
                var temp = (CurrentMovie.MoviesIMDBResultset.PopularTitles.Find(p => p.Id == ((Movie)lbPopularTitles.SelectedItem).Id));
                lbExactMatches.SelectedIndex = -1;
                lbPartialMatches.SelectedIndex = -1;
                if (CurrentMovie.MovieIMDBInfo != null && ((Movie)lbPopularTitles.SelectedItem).Id == CurrentMovie.MovieIMDBInfo.Id)
                {
                    btnApply.Enabled = false;
                    SelectedMovie = CurrentMovie.MovieIMDBInfo;
                    BindImdbMovieDetailInfoControls(SelectedMovie);
                    if (SelectedMovie.Poster == null)
                        Helpers.IMDBHelpers.download_Poster(SelectedMovie);
                    Cursor.Current = Cursors.Arrow;
                }
                else if (temp.AlreadyDownloaded)
                {
                    btnApply.Enabled = true;
                    SelectedMovie = temp;
                    BindImdbMovieDetailInfoControls(CurrentMovie.MoviesIMDBResultset.PopularTitles.Find(p => p.Id == ((Movie)lbPopularTitles.SelectedItem).Id));
                    if (temp.Poster == null)
                        Helpers.IMDBHelpers.download_Poster(temp);
                    Cursor.Current = Cursors.Arrow;
                }
                else
                {
                    btnApply.Enabled = true;
                    Imdb.GetMovieAsync(((Movie)lbPopularTitles.SelectedItem).Id, false); //0499549 avatar  //0133093 matrix
                }
            }

        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            SetChoisedMovie();
            lbMoves_SelectedIndexChanged(lbMoves, new EventArgs());
            lbMoves.Refresh();
        }

        private void SetChoisedMovie()
        {
            CurrentMovie.MovieIMDBInfo = SelectedMovie;

            if (lbPopularTitles.SelectedItem != null)
                CurrentMovie.MovieChoosedFrom = choosedFrom.PopularTitles;
            if (lbExactMatches.SelectedItem != null)
                CurrentMovie.MovieChoosedFrom = choosedFrom.ExactMatches;
            if (lbPartialMatches.SelectedItem != null)
                CurrentMovie.MovieChoosedFrom = choosedFrom.PartialMatches;

            CurrentMovie.MovieStatus = moviesStatuses.ImdbSynched;
        }

        private void BindImdbInfoControls()
        {
            if (CurrentMovie.MoviesIMDBResultset.PopularTitles != null)
            {
                lbPopularTitles.Items.AddRange(CurrentMovie.MoviesIMDBResultset.PopularTitles.ToArray());
                lbPopularTitles.DisplayMember = "Title";
                lbPopularTitles.ValueMember = "Id";
                if (CurrentMovie.MovieChoosedFrom == choosedFrom.PopularTitles)
                {
                    int tempIndex = -1;
                    foreach (Movie item in lbPopularTitles.Items)
                    {
                        if (item.Id == CurrentMovie.MovieIMDBInfo.Id)
                        {
                            tempIndex = lbPopularTitles.Items.IndexOf(item);
                        }
                    }
                    if (tempIndex != -1)
                    {
                        lbPopularTitles.SetSelected(tempIndex, true);
                        CurrentMovie.MovieStatus = moviesStatuses.ImdbSynched;
                        CurrentMovie.MovieSynhName = ((Movie)lbPopularTitles.SelectedItem).Title;
                        CurrentMovie.NewName = ((Movie)lbPopularTitles.SelectedItem).Title;
                    }
                }
            }

            if (CurrentMovie.MoviesIMDBResultset.ExactMatches != null)
            {
                lbExactMatches.Items.AddRange(CurrentMovie.MoviesIMDBResultset.ExactMatches.ToArray());
                lbExactMatches.DisplayMember = "Title";
                lbExactMatches.ValueMember = "Id";
                if (CurrentMovie.MovieChoosedFrom == choosedFrom.ExactMatches)
                {
                    int tempIndex = -1;
                    foreach (Movie item in lbExactMatches.Items)
                    {
                        if (item.Id == CurrentMovie.MovieIMDBInfo.Id)
                        {
                            tempIndex = lbExactMatches.Items.IndexOf(item);
                        }
                    }
                    if (tempIndex != -1)
                    {
                        lbExactMatches.SetSelected(tempIndex, true);
                        CurrentMovie.MovieStatus = moviesStatuses.ImdbSynched;
                        CurrentMovie.MovieSynhName = ((Movie)lbExactMatches.SelectedItem).Title;
                        CurrentMovie.NewName = ((Movie)lbExactMatches.SelectedItem).Title;
                    }

                }
            }
            if (CurrentMovie.MoviesIMDBResultset.PartialMatches != null)
            {
                lbPartialMatches.Items.AddRange(CurrentMovie.MoviesIMDBResultset.PartialMatches.ToArray());
                lbPartialMatches.DisplayMember = "Title";
                lbPartialMatches.ValueMember = "Id";
                if (CurrentMovie.MovieChoosedFrom == choosedFrom.PartialMatches)
                {
                    int tempIndex = -1;
                    foreach (Movie item in lbPartialMatches.Items)
                    {
                        if (item.Id == CurrentMovie.MovieIMDBInfo.Id)
                        {
                            tempIndex = lbPartialMatches.Items.IndexOf(item);
                        }
                    }
                    if (tempIndex != -1)
                    {
                        lbPartialMatches.SetSelected(tempIndex, true);
                        CurrentMovie.MovieStatus = moviesStatuses.ImdbSynched;
                        CurrentMovie.MovieSynhName = ((Movie)lbPartialMatches.SelectedItem).Title;
                        CurrentMovie.NewName = ((Movie)lbPartialMatches.SelectedItem).Title;
                    }
                }
            }

            if (CurrentMovie.MovieStatus == moviesStatuses.ImdbSynched && CurrentMovie.MovieIMDBInfo != null)
            {
                BindImdbMovieDetailInfoControls(CurrentMovie.MovieIMDBInfo);
            }
        }

        private void BindImdbMovieDetailInfoControls(Movie theMovie)
        {

            lbl_title.Text = theMovie.Title;
            lbl_year.Text = theMovie.Year.ToString();
            if (theMovie.Genres != null)
                lbl_genres.Text = string.Join(",", theMovie.Genres.ToArray());
            if (theMovie.ProductionCompanies != null)
                lbl_studio.Text = theMovie.ProductionCompanies.FirstOrDefault();
            lbl_rating.Text = theMovie.UserRating.ToString();
            txt_plot.Text = theMovie.Description;

            try
            {
                pictureBox1.Image = theMovie.Poster;
            }
            catch
            {
                pictureBox1.Image = null;
            }
        }

        private void btnSerialize_Click(object sender, EventArgs e)
        {
            string message = string.Empty;

            foreach (var item in VMCollection)
            {
                if (!HelperClass.SaveMovieCollectionToConfig(item))
                    message += "\r\n" + item.CurrentName;
            }

            if (!string.IsNullOrEmpty(message))
                MessageBox.Show("Error While Writing config for : \r\n" + message);
            else
                MessageBox.Show("Configs are Successfuly created");
        }

    }
}